package com.example.demo.config;

import java.io.*;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName config_helper
 * @Description
 * @date 2022/11/4 10:40
 * @Author yanceysong
 * @Version 1.0
 */
public class config_helper {
    private static final String DEST_CONFIG_PATH = "C:\\logs\\";

    /**
     * 初始化配置文件夹路径
     *
     * @param service 服务列表
     */
    private static String init_config_path(String service, String config_name) {
        File file = new File(DEST_CONFIG_PATH + service + File.separator + getToday() + File.separator + getTime() + File.separator + config_name);
        file.mkdir();
        return file.getPath();
    }

    /**
     * 获取所有服务所对应的配置文件
     *
     * @param services 服务列表
     * @return 获取好的配置文件file对象
     */
    public static Map<String, File> get_all_config(HashMap<String, HashMap<String, String>> services) {
        HashMap<String, File> result_map = new HashMap<>();
        services.forEach((service, config_map) -> {
            switch (service) {
                case "ap":
                    result_map.put(service, get_ap_config(config_map));
                    break;
                case "lp":
                    result_map.put(service, get_lp_config(config_map));
                    break;
                case "backend":
                    result_map.put(service, get_backend_config(config_map));
                    break;
                case "front":
                    result_map.put(service, get_frontend_config(config_map));
                    break;
            }
        });
        return result_map;
    }

    /**
     * 获取ap配置文件
     *
     * @param config_map 配置替换map
     * @return 获取最后的file对象
     */
    private static File get_ap_config(HashMap<String, String> config_map) {
        String config_path = init_config_path(services.AP.service_name, services.AP.config_name);
        replace_test(config_map, services.AP.config_path, config_path);
        return new File(config_path);

    }

    /**
     * 获取lp配置文件
     *
     * @param config_map 配置替换map
     * @return 获取最后的file对象
     */
    private static File get_lp_config(HashMap<String, String> config_map) {
        String config_path = init_config_path(services.LP.service_name, services.LP.config_name);
        replace_test(config_map, services.LP.config_path, config_path);
        return new File(config_path);
    }

    /**
     * 获取后端配置文件
     *
     * @param config_map 配置替换map
     * @return 获取最后的file对象
     */
    private static File get_backend_config(HashMap<String, String> config_map) {
        String config_path = init_config_path(services.BACKEND.service_name, services.BACKEND.config_name);
        replace_test(config_map, services.BACKEND.config_path, config_path);
        return new File(config_path);
    }

    /**
     * 获取前端配置文件
     *
     * @param config_map 配置替换map
     * @return 获取最后的file对象
     */
    private static File get_frontend_config(HashMap<String, String> config_map) {
        String config_path = init_config_path(services.FRONTEND.service_name, services.FRONTEND.config_name);
        replace_test(config_map, services.FRONTEND.config_path, config_path);
        return new File(config_path);
    }

    /**
     * 读取配置文件
     *
     * @param config_file_path 配置文件路径
     * @return key-value键值对
     */
    private static Map<String, String> read_config(String config_file_path) {
        Properties properties = load_config(config_file_path);
        return new HashMap<String, String>((Map) properties);
    }

    /**
     * 加载配置文件
     *
     * @param path 配置文件路径
     */
    private static Properties load_config(String path) {
        Properties properties = new Properties();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(path));
            properties.load(bufferedReader);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties;
    }

    /**
     * 将map信息写入config并生成对应文件
     *
     * @param map              待写入的map
     * @param config_file_path 生成config文件的路径
     * @return 是否写入成功
     */
    public static File write_config(HashMap<String, String> map, String config_file_path) {
        File config_file = new File(config_file_path);
        try {
            if (!(!config_file.exists() && config_file.createNewFile()))
                throw new RuntimeException("创建properties文件失败");
            //换行符
            String line = System.getProperty("line.separator");
            StringBuilder str = new StringBuilder();
            FileWriter fw = new FileWriter(config_file_path, true);
            Set<Map.Entry<String, String>> set = map.entrySet();
            for (Map.Entry<String, String> stringStringEntry : set) {
                str.append(((Map.Entry<?, ?>) stringStringEntry).getKey()).append("=").append(((Map.Entry<?, ?>) stringStringEntry).getValue()).append(line);
            }
            fw.write(str.toString());
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return config_file;
    }

    /**
     * 替换文本中字符串
     *
     * @param config_map    待替换的map
     * @param template_path 模板文本文件路径
     * @param dest_path     目标文本输出路径
     */
    public static void replace_test(HashMap<String, String> config_map, String template_path, String dest_path) {
        try {
            File file = new File(template_path);
            FileReader in = new FileReader(file);
            BufferedReader bufIn = new BufferedReader(in);
            CharArrayWriter tempStream = new CharArrayWriter();
            String line = null;
            while ((line = bufIn.readLine()) != null) {
                for (String source : config_map.keySet()) {
                    String dest = config_map.get(source);
                    line = line.replaceAll("\\$\\{" + source + "}", dest);
                }
                tempStream.write(line);
                tempStream.append(System.getProperty("line.separator"));
            }
            bufIn.close();
            File dest_file = new File(dest_path);
            dest_file.getParentFile().mkdirs();
            FileWriter out = new FileWriter(dest_path);
            tempStream.writeTo(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取现在时间精确到秒
     *
     * @return 时间戳
     */
    public static String getTime() {
        Date date = new Date();//创建时间
        SimpleDateFormat format = new SimpleDateFormat("HH：mm：ss");// 格式化时间中间不能有空格
        return format.format(date);
    }

    /**
     * 将长时间格式字符串转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param strDate 字符串时间
     * @return data
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        return formatter.parse(strDate, pos);
    }

    /**
     * 获取今天日期
     *
     * @return 今天日期
     */
    public static String getToday() {
        Date date = new Date();//创建时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }
}
